{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1 align=\"center\">Non-Rigid Registration: Free Form Deformation</h1>\n",
    "\n",
    "This notebook illustrates the use of the Free Form Deformation (FFD) based non-rigid registration algorithm in SimpleITK.\n",
    "\n",
    "The data we work with is a 4D (3D+time) thoracic-abdominal CT, the Point-validated Pixel-based Breathing Thorax Model (POPI) model. This data consists of a set of temporal CT volumes, a set of masks segmenting each of the CTs to air/body/lung, and a set of corresponding points across the CT volumes. \n",
    "\n",
    "The POPI model is provided by the Léon Bérard Cancer Center & CREATIS Laboratory, Lyon, France. The relevant publication is:\n",
    "\n",
    "J. Vandemeulebroucke, D. Sarrut, P. Clarysse, \"The POPI-model, a point-validated pixel-based breathing thorax model\",\n",
    "Proc. XVth International Conference on the Use of Computers in Radiation Therapy (ICCR), Toronto, Canada, 2007.\n",
    "\n",
    "The POPI data, and additional 4D CT data sets with reference points are available from the CREATIS Laboratory <a href=\"http://www.creatis.insa-lyon.fr/rio/popi-model?action=show&redirect=popi\">here</a>. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "library(SimpleITK)\n",
    "library(ggplot2)\n",
    "library(tidyr)\n",
    "\n",
    "# Utility method that either downloads data from the Girder repository or\n",
    "# if already downloaded returns the file name for reading from disk (cached data).\n",
    "source(\"downloaddata.R\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Utilities\n",
    "Utility methods used in the notebook for display and registration evaluation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "source(\"registration_utilities.R\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loading Data\n",
    "\n",
    "Load all of the images, masks and point data into corresponding lists. If the data is not available locally it will be downloaded from the original remote repository. \n",
    "\n",
    "Take a look at a temporal slice for a specific coronal index (center of volume). According to the documentation on the POPI site, volume number one corresponds to end inspiration (maximal air volume).\n",
    "\n",
    "You can modify the coronal index to look at other temporal slices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "simpleitk_error_allowed": "Exception in SITK"
   },
   "outputs": [],
   "source": [
    "body_label <- 0\n",
    "air_label <- 1\n",
    "lung_label <- 2    \n",
    "\n",
    "image_file_names <- file.path(\"POPI\", \"meta\", paste0(0:9, \"0-P.mhd\"))\n",
    "# Read the CT images as 32bit float, the pixel type required for registration.\n",
    "image_list <- lapply(image_file_names, function(image_file_name) ReadImage(fetch_data(image_file_name), \"sitkFloat32\"))    \n",
    "\n",
    "mask_file_names <- file.path(\"POPI\", \"masks\", paste0(0:9, \"0-air-body-lungs.mhd\"))\n",
    "mask_list <- lapply(mask_file_names, function(mask_file_name) ReadImage(fetch_data(mask_file_name)))    \n",
    "\n",
    "\n",
    "points_file_names <- file.path(\"POPI\", \"landmarks\", paste0(0:9, \"0-Landmarks.pts\"))\n",
    "points_list <- lapply(points_file_names, function(points_file_name) read.table(fetch_data(points_file_name)))\n",
    "    \n",
    "# Look at a temporal slice for the specific coronal index     \n",
    "coronal_index <- as.integer(round(image_list[[1]]$GetHeight()/2.0))\n",
    "temporal_slice <- temporal_coronal_with_overlay(coronal_index, image_list, mask_list, lung_label, -1024, 976)\n",
    "    # Flip the image so that it corresponds to the standard radiological display.\n",
    "Show(temporal_slice[,seq(temporal_slice$GetHeight(),0,-1),])  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "### Getting to know your data\n",
    "\n",
    "While the POPI site states that image number 1 is end inspiration, and visual inspection seems to suggest this is correct, we should probably take a look at the lung volumes to ensure that what we expect is indeed what is happening.\n",
    "\n",
    "Which image is end inspiration and which end expiration?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "volume_in_liters <- function(mask, label)\n",
    "{\n",
    "    label_shape_statistics_filter <- LabelShapeStatisticsImageFilter()\n",
    "    label_shape_statistics_filter$Execute(mask)\n",
    "    # 1mm^3 = 1e-6 liter\n",
    "    return (0.000001*label_shape_statistics_filter$GetPhysicalSize(label))\n",
    "}\n",
    "\n",
    "volumes <- sapply(mask_list, volume_in_liters, label=lung_label)\n",
    "lungdf <- data.frame(ImageNum=as.integer(1:length(mask_list)), Volume=volumes)\n",
    "\n",
    "# plot the original data and a smoothed version\n",
    "ggplot(lungdf, aes(x=ImageNum, y=Volume)) + geom_point() + geom_line() + ylab(\"Volume(l)\") + \n",
    "geom_smooth(method='loess')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Free Form Deformation\n",
    "\n",
    "This function will align the fixed and moving images using a FFD. If given a mask, the similarity metric will be evaluated using points sampled inside the mask. If given fixed and moving points the similarity metric value and the target registration errors will be displayed during registration. \n",
    "\n",
    "As this notebook performs intra-modal registration, we use the MeanSquares similarity metric (simple to compute and appropriate for the task)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "bspline_intra_modal_registration <- function(fixed_image, moving_image, fixed_image_mask=NULL)\n",
    "{\n",
    "    registration_method <- ImageRegistrationMethod()\n",
    "    \n",
    "    # Determine the number of Bspline control points using the physical spacing we want for the control grid. \n",
    "    grid_physical_spacing <- c(50.0, 50.0, 50.0) # A control point every 50mm\n",
    "    image_physical_size <- fixed_image$GetSize() * fixed_image$GetSpacing()\n",
    "    mesh_size <- as.integer(round(image_physical_size/grid_physical_spacing))\n",
    "\n",
    "    initial_transform <- BSplineTransformInitializer(image1 = fixed_image, \n",
    "                                                     transformDomainMeshSize = mesh_size, order=3)    \n",
    "    registration_method$SetInitialTransform(initial_transform)\n",
    "        \n",
    "    registration_method$SetMetricAsMeanSquares()\n",
    "    # Settings for metric sampling, usage of a mask is optional. When given a mask the sample points will be \n",
    "    # generated inside that region. Also, this implicitly speeds things up as the mask is smaller than the\n",
    "    # whole image.\n",
    "    registration_method$SetMetricSamplingStrategy(\"RANDOM\")\n",
    "    registration_method$SetMetricSamplingPercentage(0.01)\n",
    "    if(!is.null(fixed_image_mask))\n",
    "    {\n",
    "        registration_method$SetMetricFixedMask(fixed_image_mask)\n",
    "    }\n",
    "            \n",
    "    # Multi-resolution framework.            \n",
    "    registration_method$SetShrinkFactorsPerLevel(shrinkFactors = c(4,2,1))\n",
    "    registration_method$SetSmoothingSigmasPerLevel(smoothingSigmas=c(2,1,0))\n",
    "    registration_method$SmoothingSigmasAreSpecifiedInPhysicalUnitsOn()\n",
    "\n",
    "    registration_method$SetInterpolator(\"sitkLinear\")\n",
    "    registration_method$SetOptimizerAsLBFGSB(gradientConvergenceTolerance=1e-5, numberOfIterations=100)\n",
    "        \n",
    "    return(registration_method$Execute(fixed_image, moving_image))\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Perform Registration\n",
    "\n",
    "The following cell allows you to select the images used for registration, runs the registration, and afterwards computes statistics comparing the target registration errors before and after registration and displays a histogram of the TREs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Select the fixed and moving images, valid entries are in [1,10].\n",
    "fixed_image_index <- 1\n",
    "moving_image_index <- 8\n",
    "\n",
    "\n",
    "tx <- bspline_intra_modal_registration(fixed_image = image_list[[fixed_image_index]], \n",
    "                                      moving_image = image_list[[moving_image_index]],\n",
    "                                      fixed_image_mask = (mask_list[[fixed_image_index]] == lung_label))\n",
    "\n",
    "initial_errors <- registration_errors(Euler3DTransform(), points_list[[fixed_image_index]], points_list[[moving_image_index]])\n",
    "final_errors <- registration_errors(tx, points_list[[fixed_image_index]], points_list[[moving_image_index]])\n",
    "\n",
    "df <- data.frame(AfterRegistration=final_errors, BeforeRegistration=initial_errors)\n",
    "df.long <- gather(df, key=ErrorType, value=ErrorMagnitude)\n",
    "\n",
    "ggplot(df.long, aes(x=ErrorMagnitude, group=ErrorType, colour=ErrorType, fill=ErrorType)) + \n",
    "geom_histogram(bins=20,position='identity', alpha=0.3) + \n",
    "theme(legend.title=element_blank(), legend.position=c(.85, .85))\n",
    "## Or, if you prefer density plots\n",
    "ggplot(df.long, aes(x=ErrorMagnitude, group=ErrorType, colour=ErrorType, fill=ErrorType)) + \n",
    "geom_density(position='identity', alpha=0.3) + \n",
    "theme(legend.title=element_blank(), legend.position=c(.85, .85))\n",
    "\n",
    "cat(paste0('Initial alignment errors in millimeters, mean(std): ',\n",
    "           sprintf('%.2f',mean(initial_errors)),'(',sprintf('%.2f',sd(initial_errors)),') max:', sprintf('%.2f\\n',max(initial_errors))))\n",
    "cat(paste0('Final alignment errors in millimeters, mean(std): ',\n",
    "           sprintf('%.2f',mean(final_errors)),'(',sprintf('%.2f',sd(final_errors)),') max:', sprintf('%.2f\\n',max(final_errors))))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "Another option for evaluating the registration is to use segmentation. In this case, we transfer the segmentation from one image to the other and compare the overlaps, both visually, and quantitatively.\n",
    "\n",
    "<b>Note</b>: A more detailed version of the approach described here can be found in the [Segmentation Evaluation notebook](34_Segmentation_Evaluation.ipynb)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Transfer the segmentation via the estimated transformation. Use Nearest Neighbor interpolation to retain the labels.\n",
    "transformed_labels <- Resample(mask_list[[moving_image_index]],\n",
    "                               image_list[[fixed_image_index]],\n",
    "                               tx, \n",
    "                               \"sitkNearestNeighbor\",\n",
    "                               0.0, \n",
    "                               mask_list[[moving_image_index]]$GetPixelID())\n",
    "\n",
    "segmentations_before_and_after <- c(mask_list[[moving_image_index]], transformed_labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "simpleitk_error_allowed": "Exception in SITK"
   },
   "outputs": [],
   "source": [
    "# Look at the segmentation overlay before and after registration for a specific coronal slice\n",
    "coronal_index_registration_evaluation <- as.integer(round(image_list[[fixed_image_index]]$GetHeight()/2.0))\n",
    "temporal_slice <- temporal_coronal_with_overlay(coronal_index_registration_evaluation, \n",
    "                                                list(image_list[[fixed_image_index]], image_list[[fixed_image_index]]), \n",
    "                                                segmentations_before_and_after,\n",
    "                                                lung_label, -1024, 976)\n",
    "    # Flip the image so that it corresponds to the standard radiological display.\n",
    "Show(temporal_slice[,seq(temporal_slice$GetHeight(),0,-1),])  \n",
    "                                                                    \n",
    "# Compute the Dice coefficient and Hausdorff distance between the segmentations before, and after registration.\n",
    "ground_truth <- mask_list[[fixed_image_index]] == lung_label\n",
    "before_registration <- mask_list[[moving_image_index]] == lung_label\n",
    "after_registration <- transformed_labels == lung_label\n",
    "\n",
    "label_overlap_measures_filter <- LabelOverlapMeasuresImageFilter()\n",
    "\n",
    "label_overlap_measures_filter$Execute(ground_truth, before_registration)\n",
    "cat(paste0('Dice coefficient before registration: ', \n",
    "          sprintf(\"%.2f\\n\", label_overlap_measures_filter$GetDiceCoefficient())))\n",
    "\n",
    "label_overlap_measures_filter$Execute(ground_truth, after_registration)\n",
    "cat(paste0('Dice coefficient after registration: ', \n",
    "          sprintf(\"%.2f\\n\", label_overlap_measures_filter$GetDiceCoefficient())))\n",
    "\n",
    "hausdorff_distance_image_filter <- HausdorffDistanceImageFilter()\n",
    "\n",
    "hausdorff_distance_image_filter$Execute(ground_truth, before_registration)\n",
    "cat(paste0('Hausdorff distance before registration: ', \n",
    "          sprintf(\"%.2f\\n\", hausdorff_distance_image_filter$GetHausdorffDistance())))\n",
    "\n",
    "hausdorff_distance_image_filter$Execute(ground_truth, after_registration)\n",
    "cat(paste0('Hausdorff distance after registration: ', \n",
    "          sprintf(\"%.2f\\n\", hausdorff_distance_image_filter$GetHausdorffDistance())))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "R",
   "language": "R",
   "name": "ir"
  },
  "language_info": {
   "codemirror_mode": "r",
   "file_extension": ".r",
   "mimetype": "text/x-r-source",
   "name": "R",
   "pygments_lexer": "r",
   "version": "3.3.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
